#!/usr/bin/env node

var join = require('path').join
var fs   = require('fs')

var suppose = require('suppose')

var processArguments = require('nodeos-barebones/scripts/processArguments')


const TIMEOUT = 300  // seconds


var link = fs.readlinkSync('out/latest').split('/');

var cpu_family = link[link.length-2]
var platform   = link[link.length-1]

var type = platform.split('_')[1] || platform

var args = processArguments(process.argv.slice(2))

var cpu = args.cpu
var machine = args.machine

var exe
var timeout = setTimeout(function()
{
  exe.kill()

  console.error('Timeout while waiting an answer')
  process.exit(-2)
}, TIMEOUT*1000)


var command = 'qemu-system-'+args.cpu_family

var args =
[
//  '-enable-kvm',
  '-nographic',
]

const outDir = join('out', cpu_family, platform)
switch(type)
{
  case 'img':
    fs.accessSync(join(outDir, 'rootfs'))
    fs.accessSync(join(outDir, 'usersfs'))
    process.exit()

    // args.push('-hda', join(outDir, 'rootfs'))
    // args.push('-hdb', join(outDir, 'usersfs'))
  break

  case 'iso':
    fs.accessSync(join(outDir, 'rootfs'))
    fs.accessSync(join(outDir, 'usersfs'))
    process.exit()

//    args.push('-cdrom', join(outDir, 'rootfs'))
//    args.push('-hdb'  , join(outDir, 'usersfs'))
  break

  case 'qemu':
    var append =
    [
      'root=/dev/sda',
      'console=ttyS0'
    ]

    args.push('--kernel', join(outDir, 'barebones'),
              '--initrd', join(outDir, 'initramfs'),
              '-hda',     join(outDir, 'usersfs'),
              '-append',  append.join(' '))
  break

  case 'vagga':
    fs.accessSync(join(outDir, 'barebones'))
    fs.accessSync(join(outDir, 'initramfs'))
    fs.accessSync(join(outDir, 'usersfs'))
    process.exit()

//    args.push('-cdrom', join(outDir, 'rootfs'))
//    args.push('-hdb'  , join(outDir, 'usersfs'))
  break

  default:
    throw 'Unknown platform "'+platform+'"'
}

// // check if kvm is supported
// var kvm = /(vmx|svm)/;
// var contents = "";
//
// try
// {
//   contents = fs.readFileSync('/proc/cpuinfo');
// } catch(e){
//   throw(e);
// }
//
// if(kvm.test(contents) === false)
// {
//   // disable kvm
//   console.log("Your computer does not support kvm. NodeOS will be slower without it.");
//   args.shift();
// }

if(machine) args.unshift('-machine', machine)

exe = suppose(command, args, {debug: true, stripAnsi: true})
  .when('username:  ').respond('nodeos\n')
  .when('password:  ').respond('nodeos\n')
  .when('# ').respond('node\n')
  .when('> ').respond('setTimeout(console.log, 2000, "this is","a test")\n')
  .when(/this is a test/, function(exe)
  {
    exe.kill()
  })
  .on('error', function(error)
  {
    if(error.message.indexOf('terminating on signal 15 from pid') < 0)
      console.trace(error)
  })
  .end(function()
  {
    clearTimeout(timeout)

    var expects = this.expects.length
    if(expects) process.exit(expects)
  })
